package com.payment.web.controller.app;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.payment.common.base.AjaxResult;
import com.payment.common.type.OrderNoPrefix;
import com.payment.common.type.PaymentOrderType;
import com.payment.common.utils.StringUtils;
import com.payment.system.domain.Merchant;
import com.payment.system.domain.PaymentOrder;
import com.payment.system.domain.alipay.AliAppPayConfig;
import com.payment.system.service.IMerchantService;
import com.payment.system.service.IPaymentOrderService;
import com.payment.system.service.IWxAliPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;

/**
 * @author fuzhili
 * @Description: 微信支付宝 支付
 * @date 2019/2/16 9:15
 */
@Controller
@RequestMapping("/app/wxAliPay")
public class WxAliPayController {
    private final String gate = "https://openapi.alipay.com/gateway.do";
    private final String appId = "2019080766122404";

    @Autowired
    public IWxAliPayService wxAliPayService;
    @Autowired
    private IPaymentOrderService paymentOrderService;
    @Autowired
    private IMerchantService merchantService;

    /**
     * 购买充值订单预处理
     *
     * @return
     */
    @RequestMapping("/orderPretreatment")
    @ResponseBody
    public AjaxResult orderPretreatment(String merchantId, Integer orderType) {
        return wxAliPayService.orderPretreatment(merchantId, orderType);
    }
    
    /**
     * 购买充值订单预处理
     *
     * @return
     */
    @RequestMapping("/cancelOrder")
    @ResponseBody
    public AjaxResult cancelOrder(@RequestParam(defaultValue="")String orderId) {
    	paymentOrderService.deletePaymentOrderByIds(orderId);
        return AjaxResult.success();
    }

    
    /**
     * 微信支付 ，支付宝支付
     * mode:1微信支付  2支付宝支付
     *
     * @return
     */
    @RequestMapping("/wxAliPay")
    @ResponseBody
    public AjaxResult wxAliPay(String merchantId, String orderId, String mode) {
        return wxAliPayService.wxAliPay(merchantId, orderId, mode);
    }

    /**
     * 苹果/安卓app上架用的商城支付接口
     * 微信支付 ，支付宝支付
     * mode:1微信支付  2支付宝支付
     *
     * @return
     */
    @RequestMapping("/wxAliPaySH")
    @ResponseBody
    public AjaxResult wxAliPaySH(String merchantId, String orderId, String mode) {
        return wxAliPayService.wxAliPaySH(merchantId, orderId, mode);
    }


    @RequestMapping(value = "/test")
    public String test() {
        return "/fenxiang/details4";
    }


    @RequestMapping("/toPay")
    public ModelAndView toPay(HttpServletRequest request, HttpServletResponse response, ModelAndView mav) {
        if (request.getParameter("WIDout_trade_no") != null) {
            // 商户订单号，商户网站订单系统中唯一订单号，必填
            String out_trade_no = null;
            String body = null;
            String subject = null;
            String total_amount = null;

            out_trade_no = request.getParameter("WIDout_trade_no");
            // 订单名称，必填
            subject = request.getParameter("WIDsubject");
            // 付款金额，必填
            total_amount = request.getParameter("WIDtotal_amount");
            // 商品描述，可空
            body = request.getParameter("WIDbody");
            // 超时时间 可空
            String timeout_express = "2m";
            // 销售产品码 必填
            String product_code = "QUICK_WAP_WAY";

            String merId = "merId";
            String orderPrefix = out_trade_no.substring(0, 3);
            if (!StringUtils.equals(orderPrefix, OrderNoPrefix.PREFIX_SHANGHU.getCode())) {
                //订单预处理
                saveOrder(out_trade_no, total_amount, merId);
            }

            /**********************/
            // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
            //调用RSA签名方式
            AlipayClient alipayClient = new DefaultAlipayClient(gate, appId, AliAppPayConfig.instance().getPrivateKey(), "json", AliAppPayConfig.instance().getCharset(),
                    AliAppPayConfig.instance().getPublicKey(), "RSA2");
            AlipayTradeWapPayRequest alipay_request = new AlipayTradeWapPayRequest();

            // 封装请求支付信息
            AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
            model.setOutTradeNo(out_trade_no);
            model.setSubject(subject);
            model.setTotalAmount(total_amount);
            model.setBody(body);
            model.setTimeoutExpress(timeout_express);
            model.setProductCode(product_code);
            alipay_request.setBizModel(model);
            // 设置异步通知地址
            alipay_request.setNotifyUrl("");
            // 设置同步地址
            alipay_request.setReturnUrl("");

            // form表单生产
            String form = "";
            try {
                // 调用SDK生成表单
                form = alipayClient.pageExecute(alipay_request).getBody();
                response.setContentType("text/html;charset=" + AliAppPayConfig.instance().getCharset());
                response.getWriter().write(form);//直接将完整的表单html输出到页面
                response.getWriter().flush();
                response.getWriter().close();
            } catch (AlipayApiException | IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        mav.setViewName("fenxiang/pay");
        return mav;
    }

    private void saveOrder(String outTradeNo, String totalAmount, String merId) {

        PaymentOrder p = new PaymentOrder();
        String orderId = StringUtils.randomUUID();
        p.setId(orderId);
        p.setOrderNo(outTradeNo);
        p.setOrderStatus(0);
        p.setOrderType(PaymentOrderType.SEVEN.getCode());
        p.setAmountMoney(new BigDecimal(totalAmount));
        p.setCostRateMoney(new BigDecimal("0"));
        p.setRateMoney(new BigDecimal("0"));
        p.setProfitMoney(new BigDecimal("0"));
        p.setClearingStatus(1);
        if (StringUtils.isNotEmpty(merId)) {
            Merchant mer = merchantService.selectMerchantById(merId);
            if (mer != null) {
                p.setMerchantId(mer.getId());
                p.setMerchantName(mer.getMerchantCnName());
            }
        }
        paymentOrderService.insertPaymentOrder(p);

    }


}
